/**
 * RoleInOrganization.java
 * Purpose: Model
 *
 * @version 1.3 4/24/2011
 * @author Ahmed Mahmoud
 */

package models;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.*;

import play.db.jpa.Model;

@Entity
public class RoleInOrganization extends Model {

	@ManyToOne
	public Organization organization;

	@ManyToOne
	public User user;

	@ManyToOne
	public Role role;

	/**
	 * Constructor takes three parameters. The organization, a user in this
	 * organization and his role in the organization and adds an instance of
	 * this Record to each of the organization and user and Role.
	 * 
	 * @param organization
	 *            a certain organization.
	 * @param user
	 *            is a certain user in the organization.
	 * @param role
	 *            the role of the user in the organization.
	 */
	public RoleInOrganization(Organization organization, User user, Role role) {
		this.organization = organization;
		this.role = role;
		this.user = user;
		this.organization.addRoleAndUser(this);
		this.role.addUserAndOrganization(this);
		this.user.addRoleInOrganization(this);
	}

	/**
	 * the method takes organization and user and searches for a record that
	 * contains them then the role of this record will be the role of this user
	 * in this organization
	 * 
	 * @param organization
	 *            organization you want to get the role of the user in
	 * @param user
	 *            the user you want to get his role in the organization
	 * @return the role of this user in this organization and null if there's no
	 *         role for this user in this organization (meaning the user is not
	 *         in this organization).
	 */
	public static Role findRole(Organization organization, User user) {
		List<RoleInOrganization> list = RoleInOrganization.findAll();
		for (RoleInOrganization record : list) {
			if (record.organization.id == organization.id
					&& record.user.id == user.id) {
				return record.role;
			}
		}
		return null;
	}
	/**
	 * A method that returns all roles of all users in all organizations 
	 * @author Alaa Tarek
	 * @return list of all roles in organizations.
	 */
	public static List<RoleInOrganization> getAllRolesInOrg(){
		return RoleInOrganization.findAll();
	}
	
	/**
	 * @author Ahmed Mahmoud
	 * @return
	 * 
	 */
	public boolean cascadeDelete(){
		user.rolesAndOrganization.remove(this);
		organization.rolesAndUsers.remove(this);
		user.save();
		organization.save();
		this.delete();
		return true;
	}


}